﻿using System.Globalization;
using UnityEngine;

public static class ColorHexUtility
{
    /// <summary>
    /// 十六进制字符串转 Color（支持 #RRGGBB、#RRGGBBAA、RRGGBB 等格式）
    /// </summary>
    public static Color HexToColor(string hex)
    {
        hex = hex.Replace("#", "");
        byte r = byte.Parse(hex.Substring(0, 2), NumberStyles.HexNumber);
        byte g = byte.Parse(hex.Substring(2, 2), NumberStyles.HexNumber);
        byte b = byte.Parse(hex.Substring(4, 2), NumberStyles.HexNumber);
        byte a = hex.Length >= 8
            ? byte.Parse(hex.Substring(6, 2), NumberStyles.HexNumber)
            : (byte)255;
        return new Color(r / 255f, g / 255f, b / 255f, a / 255f);
    }

    /// <summary>
    /// Color 转十六进制字符串（格式：#RRGGBBAA）
    /// </summary>
    public static string ColorToHex(Color color)
    {
        Color32 c = color;
        return $"#{c.r:X2}{c.g:X2}{c.b:X2}{c.a:X2}";
    }
}